#!/usr/bin/python
# Filename : gentoo_report.py

import os
import sys
import commands
import subprocess
import datetime
import ftplib
from time import sleep


def usage():
	"""Explains the program to the user"""
	print \
"\n\tGentoo System Report\n" \
"\n" \
"\t", "To generate this report you will need:\n" \
"\t", "To be root!\n" \
"\t", "sys-apps/pciutils\n" \
"\t", "sys-apps/usbutils\n"

 
def check_whoami():
	"""Check if root"""
	if commands.getoutput( "whoami" ) != "root":
		sys.exit("\tSorry, You must be root!\n" )

def pn():
	"""Add new lines and the progress bar"""
	filename = "/tmp/gentoo_report.txt"
	fobj = open(filename, "a")
	newline = "\n"
	fobj.write(newline)
	fobj.close()
	sys.stdout.write("| ")
	sleep(0.1)
	sys.stdout.flush()
  
def uname_report():
	"""Generate uname -a"""
	p = subprocess.Popen("uname -a >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def uptime_report():
	"""Generate uptime"""
	p = subprocess.Popen("uptime >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def wm_version():
	"""Generate window mamnager and version"""
	path = "/etc/X11/Sessions"
	lsdir = os.listdir(path)
	for fname in lsdir:
		if fname == "Gnome":
			p = subprocess.Popen(
					"gnome-about --version | sed 's/gnome-about//' >> /tmp/gentoo_report.txt", 
					shell=True, stdout=subprocess.PIPE)
			return p.stdout.readlines()
		elif fname == "kde-3.5":
			p = subprocess.Popen(
					"kde-config --version >> /tmp/gentoo_report.txt", 
					shell=True, stdout=subprocess.PIPE)
			return p.stdout.readlines()
		elif fname == "kde-4.1":
			p = subprocess.Popen(
					"kde4-config --version >> /tmp/gentoo_report.txt", 
					shell=True, stdout=subprocess.PIPE)
			return p.stdout.readlines()
		elif fname == "kde-4.2":
			p = subprocess.Popen(
					"kde4-config --version >> /tmp/gentoo_report.txt", 
					shell=True, stdout=subprocess.PIPE)
			return p.stdout.readlines()
		elif fname == "openbox":
			p = subprocess.Popen(
					"openbox --version | sed '1!d' >> /tmp/gentoo_report.txt", 
					shell=True, stdout=subprocess.PIPE)
			return p.stdout.readlines()
		elif fname == "fluxbox":
			p = subprocess.Popen(
					"fluxbox --version >> /tmp/gentoo_report.txt", 
					shell=True, stdout=subprocess.PIPE)
			return p.stdout.readlines()
		else:
			print "No Window Manager Found."

 
def disk_report():
	"""Generate disk usage and mount points"""
	p = subprocess.Popen("df -h >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def rcupdate_report():
	"""Generate Gentoo spacific command rc-update show"""
	p = subprocess.Popen("rc-update show >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()
 
def cpuinfo_report():
	"""Generate cpu information"""
	p = subprocess.Popen("cat /proc/cpuinfo >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def emerge_report():
	"""Generate Gentoo spicific command emerge --info"""
	p = subprocess.Popen("emerge --info >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def lspci_report():
	"""Generate pci bus information"""
	p = subprocess.Popen("lspci >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def lsusb_report():
	"""Generate usb bus information"""
	p = subprocess.Popen("lsusb >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def rcconf_report():
	"""OpenRC configuration file"""
	p = subprocess.Popen(
			"sed '/^[[:space:]]*\($\|#\)/d' /etc/rc.conf >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def xorg_report():
	"""xorg-server configuration file"""
	p = subprocess.Popen(
			"sed '/^[[:space:]]*\($\|#\)/d' /etc/X11/xorg.conf >> /tmp/gentoo_report.txt", 
			shell=True, stdout=subprocess.PIPE)
	return p.stdout.readlines()

def create_date():
	"""Add current date to bottom of report"""
	now = datetime.datetime.today()
	date = now.strftime("%h %d %Y %H:%M:%S")
	handle = open("/tmp/gentoo_report.txt","a")
	logline = []
	logline.append(date)
	handle.write((" ".join(logline))+"\n")
	handle.close()        

def sendfile():
	"""Upload file to web server via ftp"""
	ftp = ftplib.FTP('wirelessfun.mobi')
	ftp.login(username, passwd)
	print "Logging into server wirelessfun ... "
	try:
		ftp.mkd(nick)
		print "Created new directory", nick
	except ftplib.error_perm, resp:
		if str(resp) == "550 Can't create directory: File exists":
			pass
		ftp.cwd(nick)
		fname = "/tmp/gentoo_report.txt"
		(head, tail) = os.path.split(fname)
		command = "STOR " + tail
		fd = open(fname, 'rb')
		temp = fd.read(2048)
		fd.seek(0, 0)
		if temp.find('\0') != -1:
			ftp.storbinary(command, fd)
		else:
			ftp.storlines(command, fd)
			ftp.close

def getdata():
	"""Run all the functions from above"""
	uname_report()
	pn()
	uptime_report()
	pn()
	disk_report()
	pn()
	wm_version()
	pn()
	rcupdate_report()
	pn()
	cpuinfo_report()
	pn()
	emerge_report()
	pn()
	lspci_report()
	pn()
	lsusb_report()
	pn()
	rcconf_report()
	pn()
	xorg_report()
	pn()
	create_date()
	pn()
	sys.stdout.write("\r")

if __name__ == "__main__":
	usage()
	check_whoami()
	nick = raw_input("Enter your nick on the Gentoo forum: ")
	directory = "/tmp/report/"
	if not os.path.exists(directory):
		os.makedirs(directory)
	make = raw_input("Enter the make of your computer: ")
	model = raw_input("Enter the model of your computer: ")
	filename = "/tmp/gentoo_report.txt"
	fobj = open(filename, "w")
	fobj.write(nick)
	fobj.write("\n")
	fobj.write(make)
	fobj.write("\n")
	fobj.write(model)
	fobj.write("\n")
	fobj.write("\n")
	fobj.close()
	username = raw_input(
			"Enter the username to upload your file: ")
	passwd = raw_input(
			"Enter the password: ")
	getdata()
	sendfile()
print    
print "Your report has been uploaded to http://wirelessfun.mobi/%s" % nick + "/gentoo_report.txt"
print

